package znbkTestPaperRdtz.fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.lancooznbk.R;
import com.example.lancooznbk.utils.DialogHelper;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.ClickImageView;
import com.example.lancooznbk.view.widget.FlowLayout;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.example.lancooznbk.view.widget.TagAdapter;
import com.example.lancooznbk.view.widget.TagFlowLayout;
import com.example.lancooznbk.view.widget.TagView;
import com.google.gson.Gson;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lancooControl.AnswerViewPagerAdapter;
import lancooControl.Control;
import lancooCustomListview.BounceListView;
import znbkTopicType.WrapBaseAdapter;
import znbkChangeZsdLearned.presenter.ZnbkSaveLearnedZsdPresenter;
import znbkTestPaperBj.entity.NotePaperEntity;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperInfor.ZnbkPaperInfor;
import znbkTestPaperRdtz.ZnbkPaperRdtzInfor;
import znbkTopicType.NoteDetailActivity;
import znbkTopicType.resContent.ZnbkContentResStlDxAdapter;
import znbkTopicType.resContent.ZnbkContentResStlZwAdapter;
import znbkTopicType.resContent.ZnbkContentResStlPptAdapter;
import znbkTopicType.resContent.ZnbkContentResStlPtAdapter;
import znbkTopicType.resContent.ZnbkContentResStlTlAdapter;
import znbkTopicType.resContent.ZnbkContentResTplAdapter;
import znbkTopicType.resContent.ZnbkContentResWblAdapter;
import znbkTopicType.resContent.ZnbkContentResYplAdapter;
import znbkTopicType.resResponse.ZnbkResponseResStlJdtAdapter;
import znbkTopicType.resResponse.ZnbkResponseResStlPptAdapter;
import znbkTopicType.resResponse.ZnbkResponseResStlTktAdapter;
import znbkTopicType.resResponse.ZnbkResponseResStlXztAdapter;

import static znbkTestPaperRdtz.activity.HeatPointExtensionPaperActivity.PAPER_FROM;
import static znbkTestPaperRdtz.activity.HeatPointExtensionPaperActivity.mEntityRdtz;

/**
 * Created by Administrator on 2018\3\14 0014.
 */

public class HeatPointExtensionPaperFragment extends BaseFragment{

    private int mNum; //页号
    private LinearLayout mLayoutTitleType;
    private TextView mTvTitleType;
    private ArrayList<View> list;
    private BounceListView LvContent;//试题主干部分
    public ViewPager VpAnswer;
    private WrapBaseAdapter mAdapter;
    private int layoutId;
    private int mModelFrom;
    private FrameLayout mFlLoading;
    private RelativeLayout relContainer;

    public static boolean IsHaveNoteRdtz = false;
    private TextView mTvTypeName;//题目类型
    private LinearLayout mLayoutBasicInfor;//基本信息：创建时间，推荐人气
    private TextView mTvCreateTime;
    private TextView mTvRecommendNumberOfTimes;
    private LinearLayout mLayoutTools;//工具栏：笔记，知识点
    private ClickImageView mCivNote;
    private ClickImageView mCivKnowledgePoint;

    private View mView;


    public static HeatPointExtensionPaperFragment newInstance(int num) {
        HeatPointExtensionPaperFragment fragment = new HeatPointExtensionPaperFragment();
        Bundle args = new Bundle();
        args.putInt("num", num);
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这里我只是简单的用num区别标签，其实具体应用中可以使用真实的fragment对象来作为叶片
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        mModelFrom = getHolderActivity().getIntent().getIntExtra(PAPER_FROM,0);
    }

    @Override
    protected void updateViews(boolean isShowLoading) {

        if(getResTypeName().equals("声文类")){
            showCommonTesePaper(false);
        }else if(getResTypeName().equals("文本类")){
            showCommonTesePaper(false);
        }else if(getResTypeName().equals("图片类")){
            showCommonTesePaper(false);
        }else if(getResTypeName().equals("试题类")){
            if(getTypeName().equals("作文")||
                    getTypeName().equals("单选题")||
                    getTypeName().equals("看图写句子")||
                    getTypeName().equals("翻译题")||
                    getTypeName().equals("语音表达")){
                VpAnswer.setVisibility(View.GONE);
                showCommonTesePaper(false);
            }else{
                VpAnswer.setVisibility(View.VISIBLE);
                showCommonTesePaper(true);
            }

        }

        relContainer.post(new Runnable() {
            @Override
            public void run() {
                mFlLoading.setVisibility(View.GONE);
                if (layoutId == R.layout.paper_zgt||layoutId == R.layout.paper_dxt) {
                    DialogHelper.showGuideOne(getHolderActivity());
                    // DialogHelper.showPopup(GuessTestingPaperFragment.this);
                }else{
                    DialogHelper.showGuideTwo(getHolderActivity());
                }
            }
        });
    }

    @Override
    public int attachLayoutRes() {

        return R.layout.znbk_paper_res;
    }


    @Override
    public void initViews(View view, Bundle savedInstanceState) {

        mView = view;
        mLayoutTitleType = (LinearLayout) view.findViewById(R.id.layout_titleType);
        mLayoutTitleType.setVisibility(View.GONE);
        mTvTitleType = (TextView) view.findViewById(R.id.tv_titleType);
        mFlLoading = (FrameLayout) view.findViewById(R.id.fl_ques_loading);
        relContainer = (RelativeLayout) view.findViewById(R.id.common_main);
        LvContent = (BounceListView) view.findViewById(R.id.listview_content);
        VpAnswer = (ViewPager) view.findViewById(R.id.viewpage_answer);

        mTvTypeName = (TextView) view.findViewById(R.id.tv_typeName);
        mLayoutBasicInfor = (LinearLayout) view.findViewById(R.id.layout_basicInfor);
        mTvCreateTime = (TextView) view.findViewById(R.id.tv_createTime);
        mTvRecommendNumberOfTimes = (TextView) view.findViewById(R.id.tv_recommendNumberOfTimer);
        mLayoutTools = (LinearLayout) view.findViewById(R.id.layout_tools);
        mCivNote = (ClickImageView) view.findViewById(R.id.civ_note);
        mCivKnowledgePoint = (ClickImageView) view.findViewById(R.id.civ_knowledgePoint);
        mCivKnowledgePoint.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                showKnowledgePointPopupWindow(mCivKnowledgePoint, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }
        });


        /*
        * 显示题型信息
        * */
        String GenreName = mEntityRdtz.getResFromTK().getGenreName();
        String TypeName = mEntityRdtz.getResFromTK().getTypeName();
        String ResName = mEntityRdtz.getResFromTK().getResName();
        if(!GenreName.equals("")){
            TypeName = GenreName;
        }
        if(TypeName.equals("")){
            mTvTypeName.setText(ResName);
        }else {
            mTvTypeName.setText(TypeName);
        }


            /*
            * 显示创建时间
            * */
            String CreateTime = ZnbkPaperRdtzInfor.CreatTime;
            if (!CreateTime.equals("")) {
                mTvCreateTime.setText("创建时间：" + CreateTime);
            } else {
                mTvCreateTime.setVisibility(View.GONE);
            }

            /*
            * 显示推荐人气
            * */
            int RecommendNumberOfTimes = ZnbkPaperRdtzInfor.RecommendNumberOfTimes;
            if (RecommendNumberOfTimes != -1) {
                String recommendPersonTime = String.format(getHolderActivity().getString(R.string.rdtz_recommendPersonTime), String.valueOf(RecommendNumberOfTimes));
                mTvRecommendNumberOfTimes.setText(recommendPersonTime);
            } else {
                mTvRecommendNumberOfTimes.setVisibility(View.GONE);
            }

            if (!mEntityRdtz.getNoteId().equals("")) {
                //获取已有学生笔记内容,显示查看图标
                IsHaveNoteRdtz = true;
            } else {
                //显示写入笔记图标
                IsHaveNoteRdtz = false;
            }


            String ResType = mEntityRdtz.getResFromTK().getResType();
            final String TypeNo = mEntityRdtz.getResFromTK().getTypeNo();
            final String QuesID = mEntityRdtz.getResFromTK().getQuesID();
            int NoteFlag= -1;

            if (ResType.equals("Q")) {
                NoteFlag = 0;
                ResType = TypeNo;
            } else {
                NoteFlag = 1;
            }

            Log.e("",""+IsHaveNoteRdtz);
            if (IsHaveNoteRdtz) {
                //获取已有学生笔记内容,显示查看图标
                mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
            } else {
                //显示写入笔记图标
                mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
            }

            final int finalNoteFlag = NoteFlag;
            mCivNote.setClickListener(new ClickImageView.ClickListener() {
                @Override
                public void onClick() {
                    getNotesData(QuesID, finalNoteFlag);
                }
            });


    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("",""+IsHaveNoteRdtz);
        if (IsHaveNoteRdtz) {
            //获取已有学生笔记内容,显示查看图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
        } else {
            //显示写入笔记图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
        }
    }


    /*
    * @@显示试卷主体
    * 实现试卷界面的布局展示
    * */
    private void showCommonTesePaper(boolean bShowChildViewPager){

         /*
        * 试题主干显示区
        * */

         if(getResTypeName().equals("文本类")) {
             mAdapter = new ZnbkContentResWblAdapter(getActivity(), 1, mNum, mModelFrom);
         }else if(getResTypeName().equals("图片类")){
             mAdapter = new ZnbkContentResTplAdapter(getActivity(), 1, mNum, mModelFrom);
         }else if(getResTypeName().equals("声文类")){
             mAdapter = new ZnbkContentResYplAdapter(getActivity(), 1, mNum, mModelFrom);
         }else if(getResTypeName().equals("试题类")){
             if(getTypeName().equals("作文")||
                     getTypeName().equals("翻译题")){
                 mAdapter = new ZnbkContentResStlZwAdapter(getActivity(), 1, mNum, mModelFrom);

             }else if(getTypeName().equals("单选题")){
                 mAdapter = new ZnbkContentResStlDxAdapter(getActivity(), 1, mNum, mModelFrom);
             }
             //听力选择
             else if(getTypeName().equals("听力选择")){
                 mAdapter = new ZnbkContentResStlTlAdapter(getActivity(), 1, mNum, mModelFrom);
             }
             //匹配题
             else if(getTypeName().equals("匹配题")){
                 mAdapter = new ZnbkContentResStlPptAdapter(getActivity(), 1, mNum, mModelFrom);
             }
             //完型选择，阅读理解,阅读填空,改错题
             else {
                 mAdapter = new ZnbkContentResStlPtAdapter(getActivity(), 1, mNum, mModelFrom);
             }
         }

        LvContent.setAdapter(mAdapter);

        if(bShowChildViewPager) {

            /*
            * 答题区
            * */
            list = new ArrayList<View>();
            list.clear();
            int sumSubject = getSubjectSum(mNum);
            for (int k = 0; k < sumSubject; k++) {

                BounceListView LvAnswer = new BounceListView(getActivity());

                if(getTypeName().equals("阅读简答")){
                    LvAnswer.setAdapter(new ZnbkResponseResStlJdtAdapter(getActivity(),1,mNum,k,mModelFrom));
                }
                //匹配题
                else if(getTypeName().equals("匹配题")){
                    LvAnswer.setAdapter(new ZnbkResponseResStlPptAdapter(getActivity(),1,mNum,k,mModelFrom));
                }
                //阅读填空，词汇填空
                else if(getTypeName().equals("阅读填空")||
                        getTypeName().equals("词汇填空")||
                        getTypeName().equals("改错题")){
                    LvAnswer.setAdapter(new ZnbkResponseResStlTktAdapter(getActivity(),1,mNum,k,mModelFrom));
                }
                //完型选择，阅读理解
                else{
                    LvAnswer.setAdapter(new ZnbkResponseResStlXztAdapter(getActivity(),1,mNum,k,mModelFrom));
                }

                list.add(LvAnswer);
            }

            VpAnswer.setAdapter(new AnswerViewPagerAdapter(list));
            VpAnswer.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    //此处添加父页面操作事件
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }


    }

    /*
    * 获取试卷总页数
    * */
    private int getQusSum(){
        return 1;
    }

    /*
    * 获取题目对应的小题数目(显示页数)
    * */
    private int getSubjectSum(int position){
        int sumSubject = -1;
        if(getTypeName().equals("改错题")||
                getTypeName().equals("阅读填空")||
                getTypeName().equals("词汇填空")){
            sumSubject = 1;
        }else if(getTypeName().equals("匹配题")){
            sumSubject = Control.backSum(mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildAnswer(),"$、")+1;
        }else {
            sumSubject = mEntityRdtz.getResFromTK().getTotalItemCount();
        }
        return sumSubject;
    }

    private String getTypeName() {
        return mEntityRdtz.getResFromTK().getTypeName();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser && mAdapter != null){//可见时进行调用
            mAdapter.pause();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAdapter != null){//不可见 暂停音乐播放
            mAdapter.pause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAdapter != null){//不可见 暂停音乐播放
            mAdapter.pause();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null) {
            mAdapter.stop();
        }
    }

    private String getResTypeName(){
        return mEntityRdtz.getResFromTK().getResTypeName();
    }

    /*****************************************************************************************************/
    /***查看笔记内容*******/
    PopupWindow popWinNotes = null;
    TextView TvNotes;
    ScaleButton SBtnChangeNotes;
    public PopupWindow showNotesPopupWindow(final View anchorView, final String noteContent,final String noteID) {
        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_notes, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
        popWinNotes = new PopupWindow(contentView,
                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        TvNotes = (TextView) contentView.findViewById(R.id.tv_notes);
        TvNotes.setText(noteContent);

        SBtnChangeNotes = (ScaleButton) contentView.findViewById(R.id.sbtn_change_notes);
        SBtnChangeNotes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWinNotes.dismiss();

                String Title = mEntityRdtz.getResFromTK().getQuesBrief();
                String ResType = mEntityRdtz.getResFromTK().getResType();
                String TypeNo = mEntityRdtz.getResFromTK().getTypeNo();
                String QuesID = mEntityRdtz.getResFromTK().getQuesID();
                if (ResType.equals("Q")) {
                    ResType = TypeNo;
                }

                NoteDetailActivity.launch(getHolderActivity(),noteContent,Title,noteID,ResType,QuesID,
                        ZnbkPaperDef.FROM_HEAT_POINT_EXTENSION);
            }
        });

        popWinNotes = new PopupWindow(contentView,
                FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popWinNotes, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popWinNotes.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popWinNotes.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popWinNotes.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popWinNotes.setFocusable(true);
//        popWinNotes.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return false;   // 这里面拦截不到返回键
//            }
//        });
        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popWinNotes.showAsDropDown(anchorView);


        return popWinNotes;
    }

    /*****fast-json 解析笔记内容******/
    private void getNotesData(String QuesID,int NoteFlag){

        String url = ZnbkPaperInfor.BaseHttpAdress+"api/ZNBK/W_ZNBK_GetPersonalNote?"+"StuID="+ UserInfo.StuId+
                "&SubjectID="+UserInfo.SubjectId+"&StageNo="+ UserInfo.StageNo+"&QuesID="+QuesID+
                "&IsReplace=true"+"&Flag="+NoteFlag;

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String arg0) {
                Log.e("==wgl==",""+arg0);//获取完成后，在 http://www.bejson.com/ 解析查看数据
                dealData(arg0);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                final String NoteId = mEntityRdtz.getNoteId();
                String ResType = mEntityRdtz.getResFromTK().getResType();
                String TypeNo =mEntityRdtz.getResFromTK().getTypeNo();
                final String Title =mEntityRdtz.getResFromTK().getQuesBrief();
                final String QuesID = mEntityRdtz.getResFromTK().getQuesID();
                if (ResType.equals("Q")) {
                    ResType = TypeNo;
                }
                NoteDetailActivity.launch(getHolderActivity(),"",Title,NoteId, ResType,QuesID,
                        ZnbkPaperDef.FROM_HEAT_POINT_EXTENSION);
            }
        });
        new Volley().newRequestQueue(getContext()).add(request);
    }


    //处理数据
    private void dealData(String result){
        Gson gson = new Gson();
        NotePaperEntity notePaperEntity = gson.fromJson(result, NotePaperEntity.class); // data 转实体
        String NoteContent = notePaperEntity.getModelNoteList().getContent();
        String NoteID = notePaperEntity.getModelNoteList().getNoteID();

        if(!NoteContent.equals("")) {
            showNotesPopupWindow(mCivNote,NoteContent,NoteID);
        }

    }

    private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {
        View upArrow = contentView.findViewById(R.id.up_arrow);
        View downArrow = contentView.findViewById(R.id.down_arrow);

        int pos[] = new int[2];
        contentView.getLocationOnScreen(pos);
        int popLeftPos = pos[0];
        anchorView.getLocationOnScreen(pos);
        int anchorLeftPos = pos[0];
        int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;
        upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
        downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

        RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
        upArrowParams.leftMargin = arrowLeftMargin;
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;
    }

/**************************************************************************************************************************/
    /******************************************查看知识点学习情况****************************************************/
    PopupWindow popWinKnowledgePoint = null;
    private TagFlowLayout mFlowLayout;
    private TextView TvKnowledgePointTitle;
    public PopupWindow showKnowledgePointPopupWindow(final View anchorView, final View.OnClickListener onClickListener) {
        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_knowledge_point, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
//        final PopupWindow popupWindow = new PopupWindow(contentView,
//                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        mFlowLayout = (TagFlowLayout) contentView.findViewById(R.id.id_flowlayout);
        TvKnowledgePointTitle = (TextView) contentView.findViewById(R.id.tv_knowledge_point_title);

        popWinKnowledgePoint = new PopupWindow(contentView,
                FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWinKnowledgePoint.dismiss();
                popWinKnowledgePoint = null;
                onClickListener.onClick(v);
            }
        });

        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popWinKnowledgePoint, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popWinKnowledgePoint.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popWinKnowledgePoint.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popWinKnowledgePoint.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popWinKnowledgePoint.setFocusable(false);
        popWinKnowledgePoint.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;   // 这里面拦截不到返回键
            }
        });
        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popWinKnowledgePoint.showAsDropDown(anchorView);

        initKnowledgePoint();

        return popWinKnowledgePoint;
    }

    /*
    * 获取知识点学习情况
    * */
    private List<String> AllTagsPosition;//整个标签存放集合
    private HashMap<Integer, Boolean> map;//记录选择的位置
    private void initKnowledgePoint(){

        AllTagsPosition = new ArrayList<>(0);
        map = new HashMap<>(0);

        int sumKnowledgePoint = mEntityRdtz.getResFromTK().getImportantZSD().size();
        for (int i = 0; i < sumKnowledgePoint; i++) {
            AllTagsPosition.add(mEntityRdtz.getResFromTK().getImportantZSD().get(i).getZSDName());
        }

        for(int i=0;i<AllTagsPosition.size();i++){
            if(!mEntityRdtz.getResFromTK().getImportantZSD().get(i).getUpdateTime().equals("")){
                map.put(i,true);
            }else{
                map.put(i,false);
            }
        }


        mFlowLayout.setAdapter(new TagAdapter<String>(AllTagsPosition.toArray(new String[AllTagsPosition.size()])) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(getHolderActivity()).inflate(R.layout.view_textview,mFlowLayout,false);
                tv.setText(s);
                return tv;
            }

        });//

        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                ((TagView)view).setChecked(true);

                int LeanedKnowledge2 =0;

                ZnbkPaperInfor.ZSDName = mEntityRdtz.getResFromTK().getImportantZSD().get(position).getZSDName();
                ZnbkPaperInfor.ZSDCode = mEntityRdtz.getResFromTK().getImportantZSD().get(position).getZSDCode();

                if(mEntityRdtz.getResFromTK().getImportantZSD().get(position).getUpdateTime().equals("")){

                    if(!map.get(position)) {
                        map.put(position, true);
                    }

                }

                for (int i = 0; i < AllTagsPosition.size(); i++) {
                    if (map.get(i)) {
                        ((TagView)mFlowLayout.getChildAt(i)).setChecked(true);
                        LeanedKnowledge2++;
                    }else {
                        ((TagView)mFlowLayout.getChildAt(i)).setChecked(false);
                    }
                }



                TvKnowledgePointTitle.setText(Html.fromHtml("知识点(共 "+AllTagsPosition.size()+
                        "个,已学习"+"<font color='#ff323d'><middle><middle>"+LeanedKnowledge2+"</middle></middle></font>"+"个,未学习"+
                        "<font color='#ff323d'><middle><middle>"+(AllTagsPosition.size()-LeanedKnowledge2)+"</middle></middle></font>"+"个)"));


                ZnbkSaveLearnedZsd();
                DictionaryActicity.startWithContent(getHolderActivity(),AllTagsPosition.get(position));

                return false;
            }
        });


        int LeanedKnowledge1 = 0;
        for (int i = 0; i < AllTagsPosition.size(); i++) {
            if (map.get(i)) {
                ((TagView)mFlowLayout.getChildAt(i)).setChecked(true);
                LeanedKnowledge1++;
            }else {
                ((TagView)mFlowLayout.getChildAt(i)).setChecked(false);
            }
        }

        TvKnowledgePointTitle.setText(Html.fromHtml("知识点(共 "+sumKnowledgePoint+
                "个,已学习"+"<font color='#ff323d'><middle><middle>"+LeanedKnowledge1+"</middle></middle></font>"+"个,未学习"+
                "<font color='#ff323d'><middle><middle>"+(sumKnowledgePoint-LeanedKnowledge1)+"</middle></middle></font>"+"个)"));

    }
    /*
    * 保存一血知识点
    * */
    ZnbkSaveLearnedZsdPresenter mZnbkSaveLearnedZsdPresenter;
    public void ZnbkSaveLearnedZsd(){
        mZnbkSaveLearnedZsdPresenter = new ZnbkSaveLearnedZsdPresenter((ILoadPaperView) getHolderActivity(),mModelFrom);
        mZnbkSaveLearnedZsdPresenter.getData(false);
    }

}